﻿using System.Collections.Generic;
using FacebookWrapper.ObjectModel;

namespace Desktop_Facebook
{
	public class FriendScoreGenerator
	{
		private const int k_ScoreLocale = 3;
		private const int k_ScoreTimezone = 7;
		private const int k_ScoreMessage = 15;
		private const int k_ScoreWallPost = 20;
		private const int k_ScoreLike = 18;
		
		private readonly Dictionary<string, FriendScore> r_Scores;

		public Dictionary<string, FriendScore> Scores
		{
			get { return r_Scores; }
		} 

		public FriendScoreGenerator()
		{
			r_Scores = new Dictionary<string, FriendScore>();
		}

		public void GenerateScores()
		{
			initalizeScores();
			if (Session.Instance.LoggedInUser != null && Session.Instance.LoggedInUser.Friends != null)
			{
				inboxScorerer();
				wallScorerer();
				localeScorerer();
			}
		}

		private void initalizeScores()
		{
			if (Session.Instance.LoggedInUser == null)
			{
				throw new System.Exception("No logged in user at FriendScoreGenerator");
			}

			Scores.Clear();
			foreach (User currentFriend in Session.Instance.LoggedInUser.Friends)
			{
				Scores.Add(currentFriend.Id, new FriendScore());
			}
		}

		private void localeScorerer()
		{
			foreach (User currentFriend in Session.Instance.LoggedInUser.Friends)
			{
				if (Scores.ContainsKey(currentFriend.Id))
				{
					if (currentFriend.Locale != null && currentFriend.Locale == Session.Instance.LoggedInUser.Locale)
					{
						Scores[currentFriend.Id].IsSameLocale = true;
					}
				} 
			}
		}

		private void wallScorerer()
		{
			if (Session.Instance.LoggedInUser.WallPosts != null)
			{
				foreach (Post wallPost in Session.Instance.LoggedInUser.WallPosts)
				{
					if (wallPost.From != null)
					{
						if (Scores.ContainsKey(wallPost.From.Id))
						{
							Scores[wallPost.From.Id].NumberOfWallPosts++;
							Scores[wallPost.From.Id].NumberOfLikes += (int)wallPost.LikesCount;
						}
					}
				}
			}
		}

		private void inboxScorerer()
		{
			if (Session.Instance.LoggedInUser.InboxThreads != null)
			{
				foreach (InboxThread currentThread in Session.Instance.LoggedInUser.InboxThreads)
				{
					if (currentThread != null)
					{
						if (Scores.ContainsKey(currentThread.From.Id))
						{
							Scores[currentThread.From.Id].NumberOfMessages++;
						}
					}
				}
			}
		}

		public class FriendScore
		{
			public bool IsSameLocale { get; set; }

            public int NumberOfMessages { get; set; }

            public int NumberOfWallPosts { get; set; }

            public int NumberOfLikes { get; set; }

			public int Score
			{
				get 
				{
					int score = 0;
					
					if (IsSameLocale)
					{
						score += k_ScoreLocale;
					}
					
					score += NumberOfMessages * k_ScoreMessage;
					score += NumberOfWallPosts * k_ScoreWallPost;
					score += NumberOfLikes * k_ScoreLike;
				
					return score;
				}
			}
		}
	}	
}